package com.sxp.servlet;

import com.sxp.bean.Book;
import com.sxp.bean.Cart;
import com.sxp.bean.User;
import com.sxp.dao.BookDao;
import com.sxp.dao.CartDao;
import com.sxp.dao.impl.BookDaoImpl;
import com.sxp.dao.impl.CartDaoImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @author hsowan
 * @date 2019-06-14
 **/
@WebServlet("/user/carts")
public class ListCartsServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        User user = (User) session.getAttribute("user");
        if (user != null) {
            CartDao cartDao = new CartDaoImpl();
            List<Cart> carts = cartDao.listByUserId(user.getId());
            double sumPrice = 0.0;

            Iterator iterator = carts.iterator();
            Cart cart = null;
            while (iterator.hasNext()) {
                cart = (Cart) iterator.next();
                if (cart.getAmount() < 1) {
                    iterator.remove();
                }
            }
            for (Cart c: carts) {
                sumPrice += c.getBookPrice() * c.getAmount();
            }
            session.setAttribute("carts", carts);
            session.setAttribute("sumPrice", sumPrice);
            req.getRequestDispatcher("/carts.jsp").forward(req, resp);

        }else {
            session.setAttribute("msg", "未登录！");
            resp.sendRedirect("/obs/message.jsp");
        }
    }
}
